package com.bruce.ai.alibaba.agentcard.register.config;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.bruce.ai.alibaba.common.properties.NacosProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

/**
 * Nacos 配置类
 * 配置 NamingService 用于服务注册和发现
 */
@Configuration
public class NacosConfig {

    @Autowired
    private NacosProperties nacosProperties;

    /**
     * 创建 NamingService Bean
     * @return NamingService 实例
     * @throws NacosException 如果创建失败
     */
    @Bean
    public NamingService namingService() throws NacosException {
        Properties properties = new Properties();
        properties.setProperty("serverAddr", nacosProperties.getServerAddr());
        
        if (nacosProperties.getNamespace() != null && !nacosProperties.getNamespace().isEmpty()) {
            properties.setProperty("namespace", nacosProperties.getNamespace());
        }
        
        if (nacosProperties.getUsername() != null && !nacosProperties.getUsername().isEmpty()) {
            properties.setProperty("username", nacosProperties.getUsername());
        }
        
        if (nacosProperties.getPassword() != null && !nacosProperties.getPassword().isEmpty()) {
            properties.setProperty("password", nacosProperties.getPassword());
        }
        
        return NacosFactory.createNamingService(properties);
    }
}